<?php
// 自定义语言包
if (!function_exists('my_translate_lang')) {
    function my_translate_lang($text, $lang)
    {
        if (dr_is_app('usu_fanyi')) {
            return \Phpcmf\Service::L('lang', 'usu_fanyi')->fanyi($text, $lang);
        }
        return $text;
    }
}


function usu_fanyi($value, $lang)
{
    // 如果目标语言与原始文本语言相同，则直接返回原始文本
    if ($lang == 'en') {
        return $value;
    }

    // 处理HTML内容
    if (preg_match("/<[a-z][\s\S]*>/i", $value)) {
        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $dom->loadHTML(mb_convert_encoding($value, 'HTML-ENTITIES', 'UTF-8'));
        libxml_clear_errors();
        $xpath = new DOMXPath($dom);
        $text_nodes = $xpath->query("//text()[normalize-space()]");
        foreach ($text_nodes as $node) {
            $translated_text = \Phpcmf\Service::L('lang', 'usu_fanyi')->zhiyi($node->nodeValue, $lang);
            if ($translated_text) {
                $node->nodeValue = $translated_text;
            }
        }
        return $dom->saveHTML();
    }

    // 处理纯文本内容
    $sentences = preg_split('/([.!?]+)/u', $value, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    $translated_text = '';

    foreach ($sentences as $key => $sentence) {
        // 仅处理句子部分（奇数索引是分隔符，偶数索引是句子）
        if ($key % 2 == 0) {
            $translated_sentence = \Phpcmf\Service::L('lang', 'usu_fanyi')->zhiyi($sentence, $lang);
            if ($translated_sentence) {
                $translated_text .= $translated_sentence;
            } else {
                $translated_text .= $sentence; // 如果无法翻译，则保持原样
            }
        } else {
            $translated_text .= $sentence; // 保留原始分隔符
        }
    }

    return $translated_text;
}
